﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KBVault.DAL.Entities;
using KBVault.DAL.Repository;
using NLog;

namespace KBVault.Web.Public.UC
{
    public partial class KBTagCloud : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    List<TagCloudItem> popularTags = TagRepository.GetPopularTags();
                    rptPopularTags.DataSource = popularTags;
                    rptPopularTags.DataBind();
                }
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex.Message);                
            }

        }

        protected void rptPopularTags_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            try
            {
                if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
                {
                    HyperLink linkToTag = (HyperLink)e.Item.FindControl("tagLink");
                    if (linkToTag != null)
                    {
                        string tagName = (e.Item.DataItem as TagCloudItem).Name;
                        int tagFrequency = (e.Item.DataItem as TagCloudItem).Count;
                        linkToTag.NavigateUrl = "/Public/ShowTag.aspx?tag="+HttpUtility.UrlEncode(tagName);
                        linkToTag.Text = tagName;
                        linkToTag.ToolTip = tagFrequency.ToString();
                        double fontSize = (tagFrequency / 10 < 1) ? ((double)tagFrequency / 10) + 1 : (tagFrequency / 10 > 2) ? 2 : ((double)tagFrequency / 10);
                        linkToTag.Style.Add("font-size", fontSize.ToString().Replace(",",".") + "em");
                        
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.GetCurrentClassLogger().Error(ex.Message);                
            }
        }
    }
}